/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Interfaz;


import ecu911.ClaseServicios;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Marcelo Montaño
 */
public class Emergencias extends javax.swing.JDialog {

    DefaultTableModel modeloTabla;
    ArrayList listaEmergencias = new ArrayList();
    ArrayList listaInstituciones = new ArrayList();
    ClaseServicios usuarioSistema = new ClaseServicios();
    Vector vectorSeleccion = new Vector();
    /**
     * Creates new form Emergencias
     */
    public Emergencias(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.getContentPane().setBackground(Color.white);
        this.btnCancelar.setBackground(Color.white);
        this.btnAgregar.setBackground(Color.white);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaEmergencias = new javax.swing.JTable();
        txtNuevaEmergencia = new javax.swing.JTextField();
        btnAgregar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        listaInstitucionesCreadas = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        listaInstitucionesSeleccionadas = new javax.swing.JList();
        btnSeleccionar = new javax.swing.JButton();
        btnQuitar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/emergencias.jpg"))); // NOI18N

        jPanel1.setBackground(new java.awt.Color(255, 102, 0));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Tipos de Urgencias Comunes");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(31, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addContainerGap())
        );

        tablaEmergencias.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tipo de urgencia"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tablaEmergencias);

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/table.gif"))); // NOI18N
        btnAgregar.setText("Agregar Nuevo");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Iconos/cancelar.gif"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(listaInstitucionesCreadas);

        jScrollPane3.setViewportView(listaInstitucionesSeleccionadas);

        btnSeleccionar.setText(">");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        btnQuitar.setText("<");
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        jLabel3.setText("Nueva Emergencia:");

        jLabel4.setText("Seleccionar instituciones que pueden auxiliar:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCancelar)
                    .addComponent(btnAgregar)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(txtNuevaEmergencia))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnSeleccionar)
                                    .addComponent(btnQuitar))
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel4)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtNuevaEmergencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(81, 81, 81)
                                .addComponent(btnSeleccionar)
                                .addGap(18, 18, 18)
                                .addComponent(btnQuitar)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING))))))
                .addGap(18, 18, 18)
                .addComponent(btnAgregar)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(btnCancelar)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-612)/2, (screenSize.height-620)/2, 612, 620);
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        cargarTablaEmergencias();
        this.llenarLista();
    }//GEN-LAST:event_formWindowOpened

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
         ArrayList respuesta = new ArrayList();
         if (this.validarCamposTextoCompleto() && this.validarSeleccionInstituciones()){    
           respuesta = usuarioSistema.crearEmergencia(String.valueOf(this.listaEmergencias.size() + 1), this.txtNuevaEmergencia.getText().toUpperCase());  //estado por default
             if(respuesta.get(0).equals("true")){
                if (vectorSeleccion.size() > 0){
                    for (int i=0; i<vectorSeleccion.size(); i++)
                    {
                        respuesta = usuarioSistema.crearServicioProblema(String.valueOf(this.listaEmergencias.size() + 1),
                                                                       String.valueOf(i+1));
                    } 
                }
                JOptionPane.showConfirmDialog(null,"Registro de emergencia correcto.",
                "Crear nueva emergencia",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null); 
                this.cargarTablaEmergencias();
                this.txtNuevaEmergencia.setText("");
                Vector v = new Vector();
                this.listaInstitucionesSeleccionadas.setListData(v);
            }
            else{
                JOptionPane.showConfirmDialog(null,respuesta.get(1),
                "Error de almacenamiento",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null); 
            }
        }
        else{
            JOptionPane.showConfirmDialog(null,"Complete toda la información.",
            "Error",JOptionPane.DEFAULT_OPTION,JOptionPane.ERROR_MESSAGE,null);
            this.pintarTextosVacios();
        }
         
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed
        // TODO add your handling code here:
        if(this.listaInstitucionesCreadas.getSelectedIndex() != -1){
            if (!vectorSeleccion.contains(this.listaInstitucionesCreadas.getSelectedValue().toString())){
                vectorSeleccion.add(this.listaInstitucionesCreadas.getSelectedValue().toString());
            }
            this.listaInstitucionesSeleccionadas.setListData(vectorSeleccion);
        }
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed
        // TODO add your handling code here:
         if(this.listaInstitucionesSeleccionadas.getSelectedIndex() != -1){
           Vector v = new Vector();
           vectorSeleccion.remove(this.listaInstitucionesSeleccionadas.getSelectedIndex());
           this.listaInstitucionesSeleccionadas.setListData(v);
           this.listaInstitucionesSeleccionadas.setListData(vectorSeleccion);
        }
    }//GEN-LAST:event_btnQuitarActionPerformed

    private void llenarLista() {
        listaInstituciones = usuarioSistema.listadoServicios();
        Vector v = new Vector();
        for (int i = 0; i<listaInstituciones.size(); i++){
            v.add(listaInstituciones.get(i).toString());
        }
        this.listaInstitucionesCreadas.setListData(v);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Emergencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Emergencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Emergencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Emergencias.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Emergencias dialog = new Emergencias(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JList listaInstitucionesCreadas;
    private javax.swing.JList listaInstitucionesSeleccionadas;
    private javax.swing.JTable tablaEmergencias;
    private javax.swing.JTextField txtNuevaEmergencia;
    // End of variables declaration//GEN-END:variables

    private void cargarTablaEmergencias() {
        ClaseServicios cliente =  new ClaseServicios();
        listaEmergencias = cliente.listadoProblemas();
        //System.out.println(listaEmergencias.size());
        DefaultTableModel temp = (DefaultTableModel)this.tablaEmergencias.getModel();
            for (int i = tablaEmergencias.getRowCount() - 1; i >= 0; i--) {
                temp.removeRow(i);
            }
            for (int i = 0; i < listaEmergencias.size(); i++) {
                Object nuevo[] = {listaEmergencias.get(i)}; //esto es por las tres columnas aunque puede variar
                temp.addRow(nuevo);
            }
            tablaEmergencias.setModel(temp);
    }
    
    private boolean validarCamposTextoCompleto(){
       boolean check = true;
       if(this.txtNuevaEmergencia.getText().compareTo("")==0){
           check = false;
       }
       return check;
   }
    
    private boolean validarSeleccionInstituciones(){
       boolean check = true;
       if(this.vectorSeleccion.size()==0){
           check = false;
       }
       return check;
   }
    
    private void pintarTextosVacios(){
       if(this.txtNuevaEmergencia.getText().compareTo("")==0){
           this.txtNuevaEmergencia.setBackground(Color.yellow);
       }
       else{
           this.txtNuevaEmergencia.setBackground(Color.white);
       }
    }
}
